/*
 * @Author: fisher
 * @Date: 2024-02-06 11:50:32
 * @LastEditors: fisher luthor-li@qq.com
 * @LastEditTime: 2024-02-12 21:26:58
 * @FilePath: \allback\controllers\AuthController.js
 * @Description:
 */
// controllers/authController.js
const AuthService = require('../services/AuthService')
/**
 * @description: 用户注册
 * @param {*} ctx
 * @return {*}
 */
exports.register = async ctx => {
  try {
    const { username, password, email } = ctx.request.body
    const res = await AuthService.register(username, email, password)
    ctx.status = 201 // Created
    ctx.body = {
      message: '注册成功!',
      status: true,
      data: {
        id: res._id,
        username: res.username,
        email: res.email
      }
    }
  } catch (err) {
    ctx.throw(err.status, err.message)
  }
}
/**
 * @description: 用户登录
 * @param {*} ctx
 * @return {*}
 */
exports.login = async ctx => {
  // 使用 AuthService 的方法来处理登录逻辑
  try {
    const { username, password } = ctx.request.body
    const res = await AuthService.login(username, password)
    ctx.status = 200
    ctx.body = {
      message: '登录成功!',
      status: true,
      data: {
        token: res
      }
    }
  } catch (err) {
    ctx.throw(err.status, err.message)
  }
}
exports.getToken = async ctx => {
  // 使用 AuthService 的方法来处理登录逻辑
  try {
    const { username, password } = ctx.request.body
    const res = await AuthService.getToken(username, password)
    ctx.status = 200
    ctx.body = {
      message: '获取token成功!',
      status: true,
      data: {
        token: res
      }
    }
  } catch (err) {
    ctx.throw(err.status, err.message)
  }
}
/**
 * @description: 用户登出
 * @param {*} ctx
 * @return {*}
 */
exports.logout = async ctx => {
  ctx.status = 200
  ctx.body = {
    message: '登出成功!',
    status: true
  }
}
/**
 * @description: 修改用户密码
 * @param {*} ctx
 * @return {*}
 */
exports.changepassword = async ctx => {
  const userId = ctx.state.user.id // 假定 JWT 验证已经填充了 ctx.state.user
  console.log('userId', userId)
  const { oldPassword, newPassword } = ctx.request.body
  try {
    // 调用 service 层更改密码
    await AuthService.changeUserPassword(userId, oldPassword, newPassword)
    ctx.response.status = 200
    ctx.body = { message: '密码修改成功', status: true }
  } catch (err) {
    ctx.throw(err.status, err.message)
  }
}
